﻿using System;
using System.Linq;
using System.Reflection;
using ClosedXML.Excel;
using SuppKids.Core.Reporting.Data;

namespace SuppKids.Core.Reporting.Excel
{
    public class AllProductsReportGenerator : ExcelReportGenerator
	{
		protected override void CreateWorkbook(out XLWorkbook workbook, out IXLWorksheet worksheet)
		{
			workbook = new XLWorkbook(Assembly.GetExecutingAssembly().GetManifestResourceStream("SuppKids.Core.Reporting.Excel.Templates.AllProductsReportTemplate.xlsx"));
            //workbook = new XLWorkbook(Assembly.GetExecutingAssembly().GetManifestResourceStream("SuppKids.Core.Reporting.Excel.Templates.SkladDailyReportTemplate.xlsx"));
			worksheet = workbook.Worksheets.FirstOrDefault() ?? workbook.Worksheets.Add(workbook.Worksheets.Count.ToString(this.FormatProvider));
		}

		protected override void CreateContent(IXLWorksheet worksheet, IReportData reportData)
		{
			var data = reportData as AllProductsReportData;
			if (data == null)
			{
				throw new InvalidOperationException("Report data is not valid for this kind of report.");
			}

            worksheet.Cell("A1").Value = "Всего продуктов: " + data.ProductsAtStorage.Count();

			var index = 4;

			var items = data.ProductsAtStorage.OrderBy(a => a.DeliveryDate).ToArray();
			var balance = 0d;
			foreach (var result in items)
			{
				balance += result.Balance;
				worksheet.Cell(string.Format("A{0}", index)).Value = result.Product.Name;
				worksheet.Cell(string.Format("B{0}", index)).Value = result.DeliveryDate;
				worksheet.Cell(string.Format("C{0}", index)).Value = result.Supplier;
				worksheet.Cell(string.Format("D{0}", index)).Value = result.Recipient;
				worksheet.Cell(string.Format("E{0}", index)).Value = result.Bill;
				worksheet.Cell(string.Format("F{0}", index)).Value = result.DeliveryAmount;
				worksheet.Cell(string.Format("G{0}", index)).Value = result.ConsumptAmount;
				worksheet.Cell(string.Format("H{0}", index)).Value = balance;
                worksheet.Cell(string.Format("I{0}", index)).Value = result.Product.Cipher;
				index++;
			}

			var range = worksheet.Range(string.Format("A4:I{0}", (index - 1)));
			range.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
			range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
			worksheet.Range("A3:I3").Style.Border.OutsideBorder = XLBorderStyleValues.Medium;
		}
	}
}
